usrName = Sys.getenv("USER")
if (usrName =='kacper'){
  path<- '/home/kacper/dev/timeser/time-series-pred/data'
}else{
  if (usrName =='mateusz')
    path<- '/home/mateusz/workspace/TS1/time-series-pred/data'
}
if(usrName =='kc262414'){
  path <-"/home/students/mismap/k/kc262414/studia/szeregi/time-series-pred/data"
}

setwd(path)

library(xts)

#USDEUR is a ﬁve minute frequency data on ﬁrst 
#(nearest to expiration) future contract (E6)
#on the EUR exchange rate
euro <- read.table("eur_2009_2010.csv", header=TRUE, sep=",")
indexEuro <- as.POSIXct(paste(euro$date,euro$time,sep=" "),
                       tz="", "%m/%d/%Y%H:%M:%S")
euro <- xts(euro$price,indexEuro)


#GOOG is a series of daily close prices adjusted for dividends
google<- read.table("GOOG_2005_2006.csv", 
                    header=FALSE, sep=",",
                    colClass=c("character", 
                               "numeric"))
IndexGoogle<-as.Date(google$V1, "%Y%m%d")
google<-xts(google$V2, IndexGoogle)

#CL is daily data on the
#ﬁrst crude oil future contract
cl<- read.table("CL_2008_2009.csv", 
                header=FALSE, sep=","
                , colClass=c("character", 
                             "numeric"))
IndexCl<-as.Date(cl$V1, "%Y%m%d")
cl<-xts(cl$V2, IndexCl)

#ZF is a monthly series on 5 year 
#US bond future, appropriately roll-adjusted
zf<- read.table("ZF_2007_2008_M.csv", 
                header=FALSE, 
                sep=",", 
                colClass=c("character", "numeric"))
IndexZf<-as.Date(zf$V1, "%Y%m%d")
zf<-xts(zf$V2, IndexZf)


#########################################

extractLastYear <-function (timeSerie){
  as.POSIXlt(index(timeSerie[length(timeSerie)]))$year
}


raw_predict <-function(timeSerieOrg, 
                       timeSerieIndex,
                       forcastingFunction,
                       maxHistory=10000,
                       transformData=function(x) return(x),
                       detransformData=NA){
  
  timeSerie <- transformData(timeSerieOrg)
  lastYear <- extractLastYear(timeSerie)
  tsLength <-length(timeSerie)
  ret <- rep(0,tsLength)
  FirstUnknown<-0
  lastMoment<-1
  
  
  while( as.POSIXlt(index(timeSerie[lastMoment]))$year < lastYear ){
    lastMoment<-lastMoment+1
  }

  FirstUnknown<-lastMoment

  for (lastMoment in FirstUnknown:tsLength){
    firstMoment<-1
    if(lastMoment-maxHistory>1){
      firstMoment<-lastMoment-maxHistory
      }
  
    ret[lastMoment]<- forcastingFunction(
      timeSerie[firstMoment:(lastMoment-1)])
  }
  
  #print(ret)  
  detransformData(ret,timeSerieOrg,FirstUnknown,timeSerieIndex)
  
}

############################## TRANS FUNC


#simple detransform fuction withoutdiffs
simDeTrans <-function(predictedTS,originalSerie,firstPredicted,timeSerieIndex){
  tsLength<-length(originalSerie)
  xts(predictedTS[firstPredicted:tsLength], timeSerieIndex[firstPredicted:tsLength])
}

#transform diff function
diffTransform<-function(timeSeries){
  diff(timeSeries)[-1]
}

#detransform diff function
diffDeTransform<-function(predictedDiffs,originalSerie,firstPredicted,timeSerieIndex){
  tsLength<-length(originalSerie)
  predictedDiffs <- xts(predictedDiffs[firstPredicted:(tsLength-1)], timeSerieIndex[(firstPredicted+1):tsLength])
  
  predictedPartMinusPeriod <- originalSerie[(firstPredicted):length(originalSerie)] 
  return(lag(predictedPartMinusPeriod)+predictedDiffs)
}

#transform diff log function
logDiffTransform<-function(timeSeries){
  tmpTimeSeries = log(timeSeries)
  diffTransform(tmpTimeSeries)
}

#detransform diff log function (exp)
logDiffDeTransform<-function(predictedSerie,originalSerie,firstPredicted,timeSerieIndex){
  tsLength<-length(originalSerie)
  predictedSerie <- xts(predictedSerie[firstPredicted:(tsLength-1)], timeSerieIndex[(firstPredicted+1):tsLength])
  
  predictedPartMinusPeriod <- log(originalSerie[(firstPredicted):length(originalSerie)])
  return(exp(lag(predictedPartMinusPeriod)+predictedSerie))
}

#transform return log function
logReturnTransform<-function(timeSeries){
  tmpTimeSeries = xts(as.vector(timeSeries[2:length(timeSeries)])/as.vector(timeSeries[1:(length(timeSeries)-1)]),index(timeSeries[-1]))
  log(tmpTimeSeries)
}

#logReturnTransform(zf)
#log(as.vector(zf[2])/as.vector(zf[1]))

#detransform return log function (exp)
logReturnDeTransform<-function(predictedSerie,originalSerie,firstPredicted,timeSerieIndex){
  predictedSerie <- exp(predictedSerie)
  tsLength<-length(originalSerie)
  predictedSerie <- xts(predictedSerie[firstPredicted:(tsLength-1)], timeSerieIndex[(firstPredicted+1):tsLength])
  
  predictedPartMinusPeriod <- originalSerie[(firstPredicted):length(originalSerie)]
  return(lag(predictedPartMinusPeriod)*predictedSerie)
}

#transform log function
logTransform<-function(timeSeries){
  log(timeSeries)
}

#logTransform(zf)

#detransform log function (exp)
logDeTransform<-function(predictedSerie,originalSerie,firstPredicted,timeSerieIndex){
  tsLength<-length(originalSerie)
  predictedSerieTmp <- xts(predictedSerie[firstPredicted:(tsLength-1)], timeSerieIndex[(firstPredicted+1):tsLength])
  return(exp(predictedSerieTmp))
}

#let's check
zf1<-zf[1:5]
zf1I <- IndexZf[1:5]
df <- diffTransform(zf1)
x<-diffDeTransform(df,zf1,2,zf1I)
if ( norm(x-zf1[-1])>0.000001){
  print(FALSE)
}


#simplest forcasting 
forcastingFunction<-function(timeSerie){
  print(timeSerie)
  1
}

# autoregressive family
autoregresiveCreator <- function(maxOrder, type) {
  return(
    function(timeSerie){
      options(warn=-1)
      sim <- ar(x=timeSerie, order.max=maxOrder, method=type, demean=FALSE)
      options(warn=1)
      gc()
      return((predict(sim, n.ahead=1)$pred)[1])
    })
}

autoSim <-autoregresiveCreator(1,'ols') 


#ret <-raw_predict(zf,index(zf),autoSim,10000,function(x) return(x), simDeTrans)
#ret2 <- raw_predict(zf,index(zf),autoSim,10000,diffTransform,diffDeTransform)

# a<-function(x){
#   return( function(y){y+ x*2} )
# }
# 
# b<-a(5); b
# b(2)

